package com.czn.shopdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czn.shopdemo.mapper.BusinessMapper;
import com.czn.shopdemo.mapper.CartMapper;
import com.czn.shopdemo.mapper.UserMapper;
import com.czn.shopdemo.model.Business;
import com.czn.shopdemo.model.Cart;
import com.czn.shopdemo.model.Goods;
import com.czn.shopdemo.model.User;
import com.czn.shopdemo.model.enums.ResultCodeEnum;
import com.czn.shopdemo.model.exception.CustomException;
import com.czn.shopdemo.model.vo.LoginVO;
import com.czn.shopdemo.service.BusinessService;
import com.czn.shopdemo.service.UserService;
import com.czn.shopdemo.utils.Encryp3DES;
import com.czn.shopdemo.utils.JwtUtil;
import com.czn.shopdemo.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author Zenan Chen
 * @date 2023/4/4 9:30
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private static final Logger log1 = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BusinessMapper businessMapper;

    @Autowired
    private CartMapper cartMapper;

    /**
     * 用户登陆校验
     *
     * @param loginVo
     * @return
     */

    @Override
    public Map<String, String> login(LoginVO loginVo) {
        HashMap<String, String> result = new HashMap<>();
        // 获取手机和验证码参数
        String account = loginVo.getAccount();
        String password = loginVo.getPassword();
        // 判断参数是否异常
        if (Utils.isEmptyStr(account) || Utils.isEmptyStr(password)) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR);
        }
        // 根据用户的账号查询用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", account);
        User user = userMapper.selectOne(queryWrapper);
        if (null == user) {
            throw new CustomException(ResultCodeEnum.USER_ACCOUNT_ERROR);
        }
        // 根据账号校验密码
        password = Encryp3DES.encryptDes(password);
        queryWrapper.eq("password", password);
        user = userMapper.selectOne(queryWrapper);
        if (null == user) {
            throw new CustomException(ResultCodeEnum.USER_PASSWORD_ERROR);
        }
        result.put("name", user.getUserName());
        //  使用jwt设置token
        String token = JwtUtil.createToken(user.getId(), user.getUserName());
        result.put("token", token);
        return result;
    }

    /**
     * 保存用户信息
     *
     * @param user
     * @throws Exception
     */
    @Override
    public void saveUser(User user) throws Exception {
        // 必填参数校验
        Utils.checkParameter(user.getAccount(), user.getPassword(), user.getUserName());
        // 先校验account是否已经存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", user.getAccount());
        User userExist = userMapper.selectOne(queryWrapper);
        if (userExist != null) {
            throw new CustomException(ResultCodeEnum.CODE_EXIST);
        }
        String password = Encryp3DES.encryptDes(user.getPassword());
        log1.info("------------------> 加密后的密码：" + password);
        user.setPassword(password);
        // 新增
        if (Utils.isEmptyStr(user.getId())) {
            user.setUuid(UUID.randomUUID().toString().replaceAll("-", ""));
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());
            userMapper.insert(user);
            //更新
        } else {
            user.setUpdateTime(new Date());
            QueryWrapper<User> updateWrapper = new QueryWrapper<>();
            updateWrapper.eq("id", user.getId());
            userMapper.update(user, updateWrapper);
        }
    }

    /**
     * 删除用户
     *
     * @param id
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteUser(String id) {
        // 先查询用户是否注册成了商家
        QueryWrapper<Business> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", id);
        List<Business> businesses = businessMapper.selectList(queryWrapper);
        if (null != businesses && businesses.size() > 0) {
            throw new CustomException("该用户已注册成了商户，无法删除！", 211);
        }
        // TODO 删除用户
        // 清除用户购物车的记录
        deleteCarts(id);
        // 删除用户
        userMapper.deleteById(id);
    }

    /**
     * 清除用户购物车的记录
     *
     * @param id
     */
    private void deleteCarts(String id) {
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", id);
        cartMapper.delete(wrapper);
    }

    /**
     * 获取用户详情
     *
     * @param id
     * @return
     */
    @Override
    public User getUserDetail(String id) {
        return userMapper.selectById(id);
    }

    /**
     * 获取用户列表
     *
     * @param pageNo
     * @param pageSize
     * @param keyword
     * @return
     */
    @Override
    public Page<User> getUserList(Integer pageNo, Integer pageSize, String keyword) {
        Page<User> page = new Page<>(pageNo, pageSize);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted", "0");
        // 根据用户名或者账号进行模糊查询
        if (!Utils.isEmptyStr(keyword)) {
            queryWrapper.eq("account", keyword).or().eq("user_name", keyword);
        }
        Page<User> userPage = userMapper.selectPage(page, queryWrapper);
        return userPage;
    }

}
